package com.quanyue.haircut.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.quanyue.auto.cache.core.CacheService;
import com.quanyue.haircut.domain.constant.CacheConstants;
import com.quanyue.haircut.service.HomeService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

@Service
public class HomeServiceImpl implements HomeService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ResourcePatternResolver resourceResolver;
    @Autowired
    private CacheService cacheService;

    @PostConstruct
    public void init() throws IOException {
        cacheService.set(CacheConstants.ATTRIBUTES_CACHE.name(), new HashMap <String, String>());
        this.resolve("css");
        this.resolve("js");
    }

    private void resolve(String type) throws IOException {
        Resource[] cssResources = resourceResolver.getResources("classpath:static/" + type + "/*");
        Type map = new TypeReference <Map <String, String>>() {
        }.getType();
        Map <String, String> attributes = cacheService.get(CacheConstants.ATTRIBUTES_CACHE.name(), map);
        for (Resource resource : cssResources) {
            String path = resource.getURI().toString();
            path = path.substring(path.lastIndexOf("/") + 1);
            attributes.put(path.substring(0, path.indexOf(".")) + StringUtils.capitalize(type), path);
        }
    }
}
